package com.zhr.tools.compile;

import java.io.*;

/**
 * 根据class路径读取class
 *
 * @author zhr
 */
public class MyClassLoader extends ClassLoader {
    @Override
    protected Class<?> findClass(String filePath) {
        File file = new File(filePath);
        String name = file.getName();
        String className = name.substring(0, name.indexOf("."));
        byte[] cLassBytes = file2Bytes(file);
        return defineClass(className, cLassBytes, 0, cLassBytes.length);
    }

    /**
     * 将文件转换成byte数组
     *
     * @param file 文件
     * @return bytes
     */
    private static byte[] file2Bytes(File file) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }
}
